<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import DialogForm from '@/components/DialogForm.vue'
import { listAddress, getAddress, addAddress, updateAddress, delAddress } from '@/api/address'
import { listUser } from '@/api/user'

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return dateTime;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 表格数据
const tableData = ref([])
// 加载状态
const loading = ref(false)
// 用户列表
const userList = ref([])
// 表格列配置
const columns = [
  { 
    prop: 'userId', 
    label: '用户名', 
    width: '120',
    formatter: (val) => {
      const user = userList.value.find(item => item.id === val)
      return user ? user.userName : ''
    }
  },
  { prop: 'recipientName', label: '收件人姓名', width: '120' },
  { prop: 'phone', label: '联系电话', width: '120' },
  { prop: 'addressDetail', label: '详细地址' },
  { 
    prop: 'isDefault', 
    label: '是否默认', 
    width: '100',
    formatter: (val) => (val === 1 ? '是' : '否')
  },
  { prop: 'createTime', label: '添加时间', width: '180', formatter: (val) => formatDateTime(val) }
]
// 搜索字段
const searchFields = ['recipientName', 'phone', 'addressDetail']

// 表单数据
const formData = reactive({
  id: null,
  userId: null,
  recipientName: '',
  phone: '',
  addressDetail: '',
  isDefault: 0,
  createTime: ''
})

// 表单字段配置 - 编辑模式
const editFormFields = ref([
  { 
    prop: 'userId', 
    label: '用户', 
    type: 'select', 
    required: true,
    options: []
  },
  { prop: 'recipientName', label: '收件人姓名', type: 'input', required: true },
  { prop: 'phone', label: '联系电话', type: 'input', required: true },
  { prop: 'addressDetail', label: '详细地址', type: 'textarea', required: true, rows: 3 },
  { 
    prop: 'isDefault', 
    label: '是否默认地址', 
    type: 'radio', 
    options: [
      { label: '否', value: 0 },
      { label: '是', value: 1 }
    ]
  }
])

// 表单字段配置 - 查看模式
const viewFormFields = ref([
  { 
    prop: 'userId', 
    label: '用户', 
    type: 'select', 
    disabled: true,
    options: []
  },
  { prop: 'recipientName', label: '收件人姓名', type: 'input', readonly: true },
  { prop: 'phone', label: '联系电话', type: 'input', readonly: true },
  { prop: 'addressDetail', label: '详细地址', type: 'textarea', readonly: true, rows: 3 },
  { 
    prop: 'isDefault', 
    label: '是否默认地址', 
    type: 'radio', 
    disabled: true,
    options: [
      { label: '否', value: 0 },
      { label: '是', value: 1 }
    ]
  },
  { prop: 'createTime', label: '添加时间', type: 'input', readonly: true }
])

// 表单规则
const formRules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  recipientName: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  addressDetail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 255, message: '长度不能超过 255 个字符', trigger: 'blur' }
  ]
}

// 对话框配置
const dialogConfig = reactive({
  visible: false,
  title: '添加地址',
  isEdit: false,
  isView: false
})

// 获取地址列表
const getAddressList = async () => {
  loading.value = true
  try {
    tableData.value = await listAddress()
  } catch (error) {
    console.error('获取地址列表失败', error)
    ElMessage.error('获取地址列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    userList.value = await listUser()
    // 更新表单字段配置中的用户选项
    const userOptions = userList.value.map(item => ({
      label: item.userName,
      value: item.id
    }))
    
    // 更新用户选项
    editFormFields.value.find(item => item.prop === 'userId').options = userOptions
    viewFormFields.value.find(item => item.prop === 'userId').options = userOptions
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 添加地址
const handleAdd = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    if (key === 'isDefault') {
      formData[key] = 0
    } else {
      formData[key] = key === 'userId' ? null : ''
    }
  })
  formData.id = null
  
  dialogConfig.title = '添加地址'
  dialogConfig.isEdit = false
  dialogConfig.isView = false
  dialogConfig.visible = true
}

// 编辑地址
const handleEdit = async (row) => {
  try {
    const res = await getAddress(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key] || ''
      })
      
      dialogConfig.title = '编辑地址'
      dialogConfig.isEdit = true
      dialogConfig.isView = false
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取地址详情失败', error)
    ElMessage.error('获取地址详情失败')
  }
}

// 查看地址
const handleView = async (row) => {
  try {
    const res = await getAddress(row.id)
    if (res) {
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = res[key] || ''
      })
      
      dialogConfig.title = '查看地址'
      dialogConfig.isEdit = false
      dialogConfig.isView = true
      dialogConfig.visible = true
    }
  } catch (error) {
    console.error('获取地址详情失败', error)
    ElMessage.error('获取地址详情失败')
  }
}

// 删除地址
const handleDelete = async (row) => {
  try {
    ElMessageBox.confirm('确定要删除该地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await delAddress(row.id)
      ElMessage.success('删除成功')
      getAddressList()
    }).catch(() => {})
  } catch (error) {
    console.error('删除地址失败', error)
    ElMessage.error('删除地址失败')
  }
}

// 批量删除地址
const handleBatchDelete = async (rows) => {
  try {
    ElMessageBox.confirm(`确定要删除选中的 ${rows.length} 个地址吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await Promise.all(rows.map(row => delAddress(row.id)))
      ElMessage.success('批量删除成功')
      getAddressList()
    }).catch(() => {})
  } catch (error) {
    console.error('批量删除地址失败', error)
    ElMessage.error('批量删除地址失败')
  }
}

// 提交表单
const handleSubmit = async (data) => {
  try {
    if (dialogConfig.isEdit) {
      // 编辑
      await updateAddress(data)
      ElMessage.success('编辑成功')
    } else {
      // 添加
      await addAddress(data)
      ElMessage.success('添加成功')
    }
    
    // 刷新列表
    getAddressList()
    // 关闭对话框
    dialogConfig.visible = false
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 切换到编辑模式
const switchToEdit = () => {
  dialogConfig.title = '编辑地址'
  dialogConfig.isEdit = true
  dialogConfig.isView = false
}

// 初始化
onMounted(async () => {
  await getUserList()
  getAddressList()
})
</script>

<template>
  <div class="address-container">
    <el-card shadow="never" class="address-card">
      <template #header>
        <div class="card-header">
          <h3>地址管理</h3>
        </div>
      </template>
      
      <!-- 表格 -->
      <data-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        @edit="handleEdit"
        @view="handleView"
        @delete="handleDelete"
        @batch-delete="handleBatchDelete"
        @refresh="getAddressList"
      />
    </el-card>
    
    <!-- 表单对话框 - 添加/编辑 -->
    <dialog-form
      v-if="!dialogConfig.isView"
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="editFormFields"
      :rules="formRules"
      @submit="handleSubmit"
    />
    
    <!-- 表单对话框 - 查看 -->
    <dialog-form
      v-else
      v-model:visible="dialogConfig.visible"
      :title="dialogConfig.title"
      v-model="formData"
      :fields="viewFormFields"
      :readonly="true"
      :show-confirm-button="false"
      :cancel-button-text="'关闭'"
    >
      <template #createTime="{ value }">
        {{ formatDateTime(value) }}
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogConfig.visible = false">关闭</el-button>
          <el-button type="primary" @click="switchToEdit">编辑</el-button>
        </div>
      </template>
    </dialog-form>
  </div>
</template>

<style scoped>
.address-container {
  height: 100%;
}

.address-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  flex: 1;
  overflow: auto;
  padding: 15px;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}
</style> 